from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from collections import defaultdict


class DelinkApplyWizard(models.TransientModel):
    _name = 'delink.apply.wizard'

    delink_mo = fields.Boolean(default=False, string='Delink Mrp')
    link_mo = fields.Boolean(default=False, string='Link Mrp')
    line_ids = fields.One2many('delink.apply.wizard.line', 'wizard_id')
    delink_apply_id = fields.Many2one('delink.apply')

    def button_confirm(self):
        line_vals = self.check_qty()
        self.delink_apply_id.line_ids = None
        self.delink_apply_id.line_ids = line_vals

    def check_qty(self):
        if not self.line_ids.filtered(lambda x: x.is_option):
            ValidationError(_('请选择要连接或断开的工单'))
        # 1 检查关联制造总数不能超过订单行数量
        vals = defaultdict(list)
        line_vals = []
        if self.link_mo:
            for line in self.line_ids:
                if not line.is_option: continue
                if not vals.get(line.sale_order_line_id, None):
                    vals[line.sale_order_line_id] = [mrp.product_qty for mrp in
                                                     line.sale_order_line_id.s_mrp_production_ids]
                vals[line.sale_order_line_id].append(line.product_qty)
                line_vals.append((0, 0, {
                    'mrp_production_id': line.mrp_production_id.id,
                    'sale_order_line_id': line.sale_order_line_id.id
                }))
            for sol, all_qty in vals.items():
                if sol.product_uom_qty < sum(all_qty):
                    raise ValidationError(_('Product {}, 关联制造数量不能超过销售订单总数'.format(sol.product_id.name)))
        else:
            line_vals = [(0, 0, {
                'mrp_production_id': line.mrp_production_id.id,
                'sale_order_line_id': line.sale_order_line_id.id
            }) for line in self.line_ids if line.is_option]
        return line_vals


class DelinkApplyWizardLine(models.TransientModel):
    _name = 'delink.apply.wizard.line'

    wizard_id = fields.Many2one('delink.apply.wizard')
    is_option = fields.Boolean()
    sale_order_line_id = fields.Many2one('sale.order.line')
    mrp_production_id = fields.Many2one('mrp.production', string='Mrp')
    state = fields.Selection(related='mrp_production_id.state', string='Mrp Statu')
    date_start = fields.Datetime(related='mrp_production_id.date_start')
    date_finished = fields.Datetime(related='mrp_production_id.date_finished')
    product_qty = fields.Float(related='mrp_production_id.product_qty')
    product_id = fields.Many2one('product.product', string='Product', related='mrp_production_id.product_id')
    product_uom_qty = fields.Float(related='sale_order_line_id.product_uom_qty', string='Order Line Qty')
